package com.tju.backend.oauth.config.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tju.backend.oauth.pojo.SysPermission;
import com.tju.backend.oauth.pojo.SysUser;
import com.tju.backend.oauth.service.SysPermissionService;
import com.tju.backend.oauth.system.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 重写 UserDetailsService 类的loadUserByUsername方法
 *
 * @Author CLS
 * @Date 2021/12/30 14:50
 */
@Slf4j
@Component("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private SysUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 通过请求的用户名去数据库中查询用户信息
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        SysUser sysUser = userMapper.selectOne(wrapper);
        findSysPermission(sysUser);
        return sysUser;
    }

    /**
     * 查询认真信息
     *
     * @param sysUser
     * @throws UsernameNotFoundException
     */
    public void findSysPermission(SysUser sysUser) throws UsernameNotFoundException {
        if (sysUser == null) {
            throw new UsernameNotFoundException("未查询到有效用户信息");
        }

        // 2. 查询该用户有哪一些权限
        List<SysPermission> sysPermissions = permissionService.findByUserId(sysUser.getId());
        // 无权限
        if (CollectionUtils.isEmpty(sysPermissions)) {
            return;
        }

        // 3. 封装用户信息和权限信息
        List<GrantedAuthority> authorities = Lists.newArrayList();
        for (SysPermission sp : sysPermissions) {
            //权限标识
            authorities.add(new SimpleGrantedAuthority(sp.getCode()));
        }
        sysUser.setAuthorities(authorities);
    }
}
